
package com.yssoft.utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;

@Component
public class MakeEncode {
	
	private static Logger logger=Logger.getLogger(UploadFile.class);
	private static String WORKDIR;
	private static final String PROGRAM_NAME = "M_";
	
	@Value("${local_path}")
	public void setWorkdir(String workdir) {
		WORKDIR = workdir;
	}
	
	/**
	 * @方法名称: QREncode
	 * @功能描述: 生成二维码
	 * @作者: 洪丰
	 * @创建时间:2018年5月14日 下午3:25:58
	 * @param content
	 * @return String
	 */
	public static String QREncode(String content){
		
		int width = 200; // 图像宽度
		int height = 200; // 图像高度
		String format = "png";// 图像类型
		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
		
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		BitMatrix bitMatrix = null;
		try {
			bitMatrix = new MultiFormatWriter().encode(content,
					BarcodeFormat.QR_CODE, width, height, hints);
		} catch (WriterException e) {
			e.printStackTrace();
			logger.info("生成矩阵失败,请重试!.");
		}// 生成矩阵
		
		String savePath = String.format("%s%s", WORKDIR, File.separatorChar);
		
		File f = new File(savePath);
		
		if (!f.exists()) {
			if (!f.mkdirs()) {
				logger.info("系统错误,创建文件保存目录失败,请重试!.");
			}
		}
		
        //文件名
  		String fileName = PROGRAM_NAME+System.currentTimeMillis() + "." + format;
  		Path path = FileSystems.getDefault().getPath(savePath, fileName);
  		
		try {
			MatrixToImageWriter.writeToPath(bitMatrix, format, path);
		} catch (IOException e) {
			e.printStackTrace();
			logger.info("生成二维码失败,请重试!");
		}
		return "/files/"+fileName;
	}
	
	/**
	 * @方法名称: barEncode
	 * @功能描述: 生成条形码
	 * @作者: 洪丰
	 * @创建时间:2018年5月14日 下午3:32:21
	 * @param content
	 * @return String
	 */
	public static String barEncode(String content){
		int width = 335; // 图像宽度
		int height = 150; // 图像高度
		String format = "png";// 图像类型
		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
		
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		BitMatrix bitMatrix = null;
		try {
			bitMatrix = new MultiFormatWriter().encode(content,
					BarcodeFormat.CODE_128, width, height, hints);
		} catch (WriterException e) {
			e.printStackTrace();
			logger.info("生成矩阵失败,请重试!.");
		}// 生成矩阵
		
		String savePath = String.format("%s%s", WORKDIR, File.separatorChar);
		
		File f = new File(savePath);
		
		if (!f.exists()) {
			if (!f.mkdirs()) {
				logger.info("系统错误,创建文件保存目录失败,请重试!.");
			}
		}
		
        //文件名
  		String fileName = PROGRAM_NAME+System.currentTimeMillis() + "." + format;
  		Path path = FileSystems.getDefault().getPath(savePath, fileName);
  		
		try {
			MatrixToImageWriter.writeToPath(bitMatrix, format, path);
		} catch (IOException e) {
			e.printStackTrace();
			logger.info("生成二维码失败,请重试!");
		}
		return "/files/"+fileName;
	}

	/**
	 * @方法名称: decode
	 * @功能描述: 解析图像
	 * @作者: 洪丰
	 * @创建时间:2018年5月14日 下午3:25:21
	 * @param fileName
	 * @return String
	 */
	public static String decode(String fileName) {
		String path = String.format("%s%s", WORKDIR, File.separatorChar);
		BufferedImage image;
		try {
			
			path = path + fileName;
			image = ImageIO.read(new File(path));
			LuminanceSource source = new BufferedImageLuminanceSource(image);
			Binarizer binarizer = new HybridBinarizer(source);
			BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
			Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
			hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
			Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码
		    String content = result.getText();
			//System.out.println("图片中内容：	");
			//System.out.println("author：	" + content.getString("author"));
			//System.out.println("zxing：	" + content.getString("zxing"));
			//System.out.println("图片中格式：	");
			//System.out.println("encode：	" + result.getBarcodeFormat());
			return content;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
}

